package com.lovol.gis.demo.common;

import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
import org.locationtech.jts.geom.Envelope;

public class RasterUtil {

    static {
        gdal.AllRegister();
    }


    /**
     * 获取栅格数据在4326坐标系下的空间范围
     *
     * @param path 栅格数据路径
     * @return 返回栅格数据的外接矩形
     */
    public static Envelope getRasterBoundsIn4326(String path) {
        Dataset dataset = null;
        try {
            dataset = gdal.Open(path, gdalconst.GA_ReadOnly);
            if (dataset == null) {
                System.err.println(gdal.GetLastErrorMsg());
                return null;
            }
            return getRasterBoundsIn4326(dataset);
        } catch (Exception ex) {
            return null;
        } finally {
            if (dataset != null) {
                dataset.delete();
            }
        }
    }

    /**
     * 获取栅格数据在4326坐标系下的范围
     *
     * @param dataset 输入栅格数据
     * @return 返回范围
     */
    public static Envelope getRasterBoundsIn4326(Dataset dataset) {
        try {
            boolean is4326 = true;
            String strProj = dataset.GetProjection();
            int pos = strProj.lastIndexOf("EPSG");
            if (pos != -1) {
                String sub = strProj.substring(pos);
                if (sub.indexOf("4326") == -1) {
                    is4326 = false;
                }
            }
            int columns = dataset.getRasterXSize();
            int rows = dataset.getRasterYSize();
            double[] geoTransforms = dataset.GetGeoTransform();
            double xmin = geoTransforms[0];
            double xmax = xmin + columns * geoTransforms[1];
            double ymax = geoTransforms[3];
            double ymin = ymax + rows * geoTransforms[5];
            Envelope envelope = new Envelope(xmin, xmax, ymin, ymax);
            if (!is4326) {
                SrsUtil srsUtil = new SrsUtil();
                srsUtil.setSourceWkt(strProj);
                srsUtil.setTargetode("EPSG:4326");
                return srsUtil.reproject(envelope);
            } else
                return envelope;
        } catch (Exception ex) {
            return null;
        }
    }
}
